package com.dengqi.mymodule.activity.fragment.tabframe;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dengqi.mymodule.R;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * @Author: dengqi
 * @CreateDate: 2020/11/18 9:17
 * @Description: FrameLayout+tabLayout模式
 */
public class QTabFrameLayout extends LinearLayout {

    private TabLayout mTabLayout;
    private FragmentManager mFragmentManager;
    private Fragment mLastFragment;
    private int mLastPosition=-1;
    private List<Fragment> mFragments = new ArrayList<>();
    //中间多出一块
    private ImageView mCenterView;
    private OnItemClickListener onItemClickListener;//单击事件


    public QTabFrameLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(LinearLayout.VERTICAL);
        LayoutInflater.from(context).inflate(R.layout.view_q_tabframelayout, this, true);
        mCenterView = findViewById(R.id.iv_center);
        mTabLayout = findViewById(R.id.tabLayout);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if(mLastPosition == position){
                    return;
                }
                if(onItemClickListener!=null){
                    boolean isIntercept = onItemClickListener.onItemClick(position);
                    if(!isIntercept){
                        changeFragment(position);
                    }else{
                        mTabLayout.selectTab(mTabLayout.getTabAt(mLastPosition));
                    }
                }else{
                    changeFragment(position);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 设置TabLayout背景色
     * @param resId
     */
    public void setTabLayoutBackground(int resId){
        mTabLayout.setBackgroundResource(resId);
    }

    /**
     * 更新tabview数字
     * @param position
     * @param num
     */
    public void setTabViewNumByIndex(int position, int num) {
        TabLayout.Tab tab = getCorrectTabView(position);
        TextView tvNum = tab.view.findViewById(R.id.tv_num);
        tvNum.setVisibility(num==0?GONE:VISIBLE);
        tvNum.setText(String.valueOf(num));
    }

    /**
     * 绑定TabBean集合
     * @param fragmentManager
     * @param tabList
     */
    public void setTabViewData(FragmentManager fragmentManager, List<TabBean> tabList, List<Fragment> fragments) {
        this.mFragmentManager = fragmentManager;
        this.mFragments = fragments;
        for(int i = 0; i < tabList.size(); i++){
            TabBean tabBean = tabList.get(i);
            mTabLayout.addTab(mTabLayout.newTab().setCustomView(createTabView(tabBean)), i==0);
        }
    }

    /**
     * 先调用bindData再调用
     * @param resId
     * @param listener
     */
    public void setCenterView(int resId, OnClickListener listener) {
        mCenterView.setVisibility(VISIBLE);
        mCenterView.setImageResource(resId);
        View empty = new View(getContext());
        empty.setOnClickListener(listener);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(empty) ,mTabLayout.getTabCount()/2);
    }

    /**
     * 点击事件
     * @param listener
     */
    public void setTabViewClickListener(OnItemClickListener listener){
        this.onItemClickListener = listener;
    }


    /**
     * 创建自定义tabview
     * @param tabBean
     * @return
     */
    private View createTabView(TabBean tabBean) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_q_tab, null, false);
        ImageView ivIcon = view.findViewById(R.id.iv_icon);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        TextView tvNum = view.findViewById(R.id.tv_num);
        //图标
        ivIcon.setVisibility(tabBean.iconRes==0?GONE:VISIBLE);
        ivIcon.setImageResource(tabBean.iconRes);
        //文字
        tvTitle.setVisibility(TextUtils.isEmpty(tabBean.title)?GONE:VISIBLE);
        tvTitle.setText(tabBean.title);
        tvTitle.setTextColor(getContext().getResources().getColorStateList(tabBean.textRes));
        //数量
        tvNum.setVisibility(tabBean.num==0?GONE:VISIBLE);
        tvNum.setText(String.valueOf(tabBean.num));
        return view;
    }

    /**
     * 判断centerview是否存在
     * 存在并返回修正Fragment
     * @return
     */
    private Fragment getCorrectFragment(int position){
        int tabCount = mTabLayout.getTabCount();
        if(mCenterView!=null && mCenterView.getVisibility()==VISIBLE){
            if(position < (tabCount-1)/2){
                return mFragments.get(position);
            }else{
                return mFragments.get(position-1);
            }
        }
        return mFragments.get(position);
    }

    /**
     * 判断centerview是否存在
     * 存在并返回修正TabView
     * @return
     */
    private TabLayout.Tab getCorrectTabView(int position){
        int tabCount = mTabLayout.getTabCount();
        if(mCenterView!=null && mCenterView.getVisibility()==VISIBLE){
            if(position < (tabCount-1)/2){
                return mTabLayout.getTabAt(position);
            }else{
                return mTabLayout.getTabAt(position+1);
            }
        }
        return mTabLayout.getTabAt(position);
    }

    private void changeFragment(int position) {
        Fragment newFragment = getCorrectFragment(position);
        if(mLastFragment!=newFragment){
            //开启事务
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            //隐藏当前Fragment
            if(mLastFragment!=null){
                ft.detach(mLastFragment);
            }
            //判断Fragment是否已经添加
            if (!newFragment.isAdded()) {
                ft.add(android.R.id.tabcontent, newFragment);
            }
            //显示新的Fragment
            ft.attach(newFragment);
            ft.commit();
            mLastFragment = newFragment;
            mLastPosition = position;
        }
    }

    public interface OnItemClickListener {
        boolean onItemClick(int position);
    }

    public static class TabBean {
        private String title; //文字
        private int textRes; //文字选中颜色
        private int iconRes; //图片
        private int num; //数量

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getTextRes() {
            return textRes;
        }

        public void setTextRes(int textRes) {
            this.textRes = textRes;
        }

        public int getIconRes() {
            return iconRes;
        }

        public void setIconRes(int iconRes) {
            this.iconRes = iconRes;
        }
    }
}
